<template>
  <div class="layout-container">
    <!-- 顶部导航栏 -->
    <header class="header">
      <div class="logo">
        <span>潍坊理工小助手</span>
      </div>
      <div class="user-wrapper">
        <!-- 未登录状态 -->
        <el-button v-if="!isLoggedIn" type="primary" @click="showLoginModal">
          登录
        </el-button>
        
        <!-- 已登录状态 -->
        <el-dropdown v-else @command="handleCommand">
          <span class="user-dropdown">
            <el-avatar :size="32" icon="UserFilled" />
            <span class="username">{{ username }}</span>
          </span>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="profile">个人信息</el-dropdown-item>
              <el-dropdown-item command="logout">退出登录</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </header>

    <!-- 登录弹窗 -->
    <el-dialog
      v-model="loginVisible"
      title="用户登录"
      width="460px"
      :close-on-click-modal="false"
      :show-close="true"
      destroy-on-close
      class="login-dialog"
    >
      <login-modal 
        @login-success="handleLoginSuccess"
        @switch-to-register="switchToRegister"
      />
    </el-dialog>

    <!-- 注册弹窗 -->
    <el-dialog
      v-model="registerVisible"
      title="用户注册"
      width="460px"
      :close-on-click-modal="false"
      :show-close="true"
      destroy-on-close
      class="login-dialog"
    >
      <register-modal 
        @register-success="handleRegisterSuccess"
        @switch-to-login="switchToLogin"
      />
    </el-dialog>

    <div class="main-content">
      <!-- 侧边栏 -->
      <aside class="sidebar" :class="{ 'collapsed': isSidebarCollapsed }">
        <div class="sidebar-header">
          <el-button 
            class="new-chat-btn" 
            @click="clearChat" 
            type="primary" 
            :icon="Plus"
          >
            <span v-show="!isSidebarCollapsed">新对话</span>
          </el-button>
          <el-button 
            class="collapse-btn" 
            @click="toggleSidebar" 
            :icon="isSidebarCollapsed ? ArrowRight : ArrowLeft"
          />
        </div>

        <div class="menu-items">
          <router-link to="/chat" class="menu-item" active-class="active">
            <el-icon><ChatLineRound /></el-icon>
            <span v-show="!isSidebarCollapsed">聊天</span>
          </router-link>
          <router-link to="/activity" class="menu-item" active-class="active">
            <el-icon><Calendar /></el-icon>
            <span v-show="!isSidebarCollapsed">活动</span>
          </router-link>
        </div>
      </aside>

      <!-- 主要内容区域 -->
      <main class="content" :class="{ 'content-expanded': isSidebarCollapsed }">
        <router-view #default="{ Component }">
          <keep-alive>
            <component :is="Component" ref="currentComponent" />
          </keep-alive>
        </router-view>
      </main>
    </div>
  </div>
</template>

<script>
import { defineComponent, ref, onMounted, nextTick } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Plus, ArrowRight, ArrowLeft, ChatLineRound, Calendar } from '@element-plus/icons-vue'
import { getToken, removeToken } from '@/utils/auth'
import LoginModal from './auth/LoginModal.vue'
import RegisterModal from './auth/RegisterModal.vue'
import request from '@/utils/request'

export default defineComponent({
  name: 'MainLayout',
  components: {
    LoginModal,
    RegisterModal,
    Plus,
    ArrowRight,
    ArrowLeft,
    ChatLineRound,
    Calendar
  },
  setup() {
    const router = useRouter()
    const route = useRoute()
    const isSidebarCollapsed = ref(false)
    const username = ref('用户')
    const currentComponent = ref(null)
    const loginVisible = ref(false)
    const registerVisible = ref(false)
    const isLoggedIn = ref(!!getToken())

    // 从localStorage加载侧边栏状态
    onMounted(() => {
      const savedState = localStorage.getItem('sidebarState')
      if (savedState) {
        isSidebarCollapsed.value = JSON.parse(savedState)
      }
      if (isLoggedIn.value) {
        getUserInfo()
      }
    })

    // 切换侧边栏
    const toggleSidebar = () => {
      isSidebarCollapsed.value = !isSidebarCollapsed.value
      localStorage.setItem('sidebarState', JSON.stringify(isSidebarCollapsed.value))
      window.dispatchEvent(new Event('resize'))
    }

    // 清除聊天
    const clearChat = async () => {
      // 先切换到聊天页面
      if (route.path !== '/chat') {
        await router.push('/chat')
      }
      
      // 等待组件挂载完成
      nextTick(() => {
        const chatComponent = currentComponent.value
        if (chatComponent) {
          // 重置聊天组件状态
          if (typeof chatComponent.resetChat === 'function') {
            chatComponent.resetChat()
            ElMessage.success('已开启新对话')
          } else {
            console.warn('ChatBox组件未提供resetChat方法')
          }
        } else {
          console.warn('未找到ChatBox组件引用')
        }
      })
    }

    // 显示登录弹窗
    const showLoginModal = () => {
      loginVisible.value = true
    }

    // 切换到注册
    const switchToRegister = () => {
      loginVisible.value = false
      registerVisible.value = true
    }

    // 切换到登录
    const switchToLogin = () => {
      registerVisible.value = false
      loginVisible.value = true
    }

    // 获取用户信息
    const getUserInfo = async () => {
      try {
        const res = await request.get('/getInfo')
        if (res.code === 200) {
          if (res.user) {
            username.value = res.user.userName || '用户'
          }
        } else {
          console.error('获取用户信息失败:', res.msg)
          // 如果获取用户信息失败，可能是 token 失效
          if (res.code === 401) {
            removeToken()
            isLoggedIn.value = false
            router.push('/chat')
          }
        }
      } catch (error) {
        console.error('获取用户信息失败:', error)
        if (error.response?.status === 401) {
          removeToken()
          isLoggedIn.value = false
          router.push('/chat')
        }
      }
    }

    // 处理登录成功
    const handleLoginSuccess = async () => {
      isLoggedIn.value = true
      loginVisible.value = false
      await getUserInfo()
      ElMessage.success('登录成功')
    }

    // 处理注册成功
    const handleRegisterSuccess = () => {
      ElMessage.success('注册成功')
    }

    // 修改处理下拉菜单命令
    const handleCommand = (command) => {
      switch (command) {
        case 'profile':
          // 处理个人信息
          break
        case 'logout':
          removeToken()
          isLoggedIn.value = false
          username.value = '用户' // 重置用户名
          router.push('/chat') // 可选：重定向到聊天页面
          ElMessage.success('退出成功')
          break
      }
    }

    return {
      isSidebarCollapsed,
      username,
      currentComponent,
      loginVisible,
      registerVisible,
      isLoggedIn,
      toggleSidebar,
      clearChat,
      handleCommand,
      showLoginModal,
      switchToRegister,
      switchToLogin,
      handleLoginSuccess,
      handleRegisterSuccess,
      Plus,
      ArrowRight,
      ArrowLeft
    }
  }
})
</script>

<style scoped>
.layout-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
}

.header {
  height: 60px;
  background-color: #fff;
  border-bottom: 1px solid #e6e6e6;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 20px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
}

.logo {
  font-size: 20px;
  font-weight: bold;
  color: #333;
}

.user-wrapper {
  display: flex;
  align-items: center;
}

.user-dropdown {
  display: flex;
  align-items: center;
  cursor: pointer;
}

.username {
  margin-left: 8px;
  color: #333;
}

.main-content {
  flex: 1;
  display: flex;
  overflow: hidden;
  position: relative;
}

.sidebar {
  position: fixed;
  height: calc(100vh - 60px);
  width: 240px;
  background-color: #f5f7f9;
  border-right: 1px solid #e6e6e6;
  transition: all 0.3s;
  display: flex;
  flex-direction: column;
  z-index: 100;
}

.sidebar.collapsed {
  width: 64px;
  overflow: visible;
}

.sidebar-header {
  padding: 16px;
  display: flex;
  gap: 8px;
  position: relative;
}

.new-chat-btn {
  flex: 1;
  min-width: 0;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.collapsed .new-chat-btn {
  padding: 8px;
  flex: 0;
  width: 32px;
  min-width: 32px;
}

.collapsed .new-chat-btn span {
  display: none;
}

.collapse-btn {
  flex-shrink: 0;
  width: 32px;
  min-width: 32px;
  padding: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  z-index: 1000;
}

.collapsed .collapse-btn {
  position: absolute;
  right: -40px;
  top: 16px;
  background-color: #f5f7f9;
  border: 1px solid #e6e6e6;
  border-left: none;
  border-radius: 0 6px 6px 0;
  box-shadow: 2px 0 4px rgba(0, 0, 0, 0.1);
}

.collapsed .collapse-btn:hover {
  background-color: #e6e6e6;
}

.menu-items {
  padding: 8px;
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.menu-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px;
  color: #666;
  text-decoration: none;
  border-radius: 6px;
  transition: all 0.3s;
}

.menu-item:hover {
  background-color: #e6e6e6;
}

.menu-item.active {
  background-color: #ecf5ff;
  color: #409eff;
}

.content {
  flex: 1;
  overflow: auto;
  padding: 20px;
  background-color: #fff;
  margin-left: 240px;
  transition: all 0.3s;
  min-height: calc(100vh - 60px);
}

.content-expanded {
  margin-left: 64px;
}

:deep(.login-dialog) {
  border-radius: 8px;
}

:deep(.login-dialog .el-dialog__header) {
  margin: 0;
  padding: 20px 30px;
  border-bottom: 1px solid #f0f0f0;
}

:deep(.login-dialog .el-dialog__body) {
  padding: 0;
}

:deep(.login-dialog .el-dialog__headerbtn) {
  top: 20px;
  right: 20px;
}
</style> 